package com.chain.BrotherExchange.ui.window;

import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.QuotationTypes;
import com.chain.BrotherExchange.viewmodel.QuotationViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.chain.BrotherExchange.widget.CompatPopupWindow;
import com.example.common.widget.state.NetworkStateLayout;

public class TokenTypeWindow {

    private View.OnClickListener mOnClickListener;
    private final FragmentActivity mActivity;
    private final QuotationViewModel mViewModel;
    private final CompatPopupWindow mPopupWindow;
    private final NetworkStateLayout mRootStateLayout;

    public TokenTypeWindow(FragmentActivity activity) {
        this.mActivity = activity;
        mViewModel = ViewModelProviders.of(activity).get(QuotationViewModel.class);
        mRootStateLayout = (NetworkStateLayout) LayoutInflater.from(mActivity).inflate(R.layout.window_token_name_list,
                null);

        mPopupWindow = new CompatPopupWindow(mRootStateLayout,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);

        initQuestionTitle(mRootStateLayout.findViewById(R.id.radio_group));

        mRootStateLayout.setOnClickListener(v -> mPopupWindow.dismiss());
    }

    private void initQuestionTitle(RadioGroup group) {
        mViewModel.quotationTypes().observe(mActivity, resource ->
                Resource.load(mActivity, resource, mRootStateLayout, result -> {
                    for (QuotationTypes.DataBean.ListBean list : result) {
                        group.addView(createMenuItem(group, list.getMark(), list.getToken_id()));
                    }

                    group.getChildAt(0).performClick();
                })
        );
    }

    public void setOnClickListener(View.OnClickListener onClickListener) {
        this.mOnClickListener = onClickListener;
    }

    private RadioButton createMenuItem(RadioGroup group, String text, int id) {
        RadioButton view = (RadioButton) LayoutInflater.from(mActivity)
                .inflate(R.layout.layout_question_menu_radio_button, group, false);
        view.setText(text);
        view.setTag(id);
        view.setOnClickListener(v -> {
            mPopupWindow.dismiss();
            this.mOnClickListener.onClick(v);
        });
        return view;
    }

    public void show(View anchor) {
        mPopupWindow.showAsDropDown(anchor);
    }
}
